/**
 * @author Fayçal INAJJARANE
 */
package com.appspot.finajjarane.framework.service.impl;

import java.net.URL;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.appspot.finajjarane.framework.generic.ApplicationConstants;
import com.appspot.finajjarane.framework.generic.Utils;
import com.appspot.finajjarane.framework.service.IPicasaWeb;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.media.mediarss.MediaContent;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.util.AuthenticationException;


@Service
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class PicasaWebImpl implements IPicasaWeb {

	private PicasawebService picasawebService;

	private List<PhotoEntry> photos = null;

	private Date lastUpdate = new Date();

	public PicasaWebImpl() throws AuthenticationException{
		this.picasawebService = new PicasawebService("faycal-inajjarane.appspot.com");
		this.picasawebService.setUserCredentials(ApplicationConstants.PICASA_WEB_USERNAME, ApplicationConstants.PICASA_WEB_PASSWORD);
	}

	@Override
	public String getImageUrl(final String imageTitle) {

		String defaultImage = ApplicationConstants.NO_IMAGE_FULL_LINK ;

		try{
			if(null == this.photos || Utils.getDatesDifferenceInSenconds(this.lastUpdate, new Date(), true)>ApplicationConstants.PICASA_SECONDES_REFRESH_ALBUM ){


			URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" 	+
						ApplicationConstants.PICASA_WEB_USERNAME_SHORT 		+
						"/albumid/" + ApplicationConstants.PICASA_MAIN_ALBUM_ID );

			AlbumFeed mainAlbum = this.picasawebService.getFeed(feedUrl, AlbumFeed.class);

			this.photos = mainAlbum.getPhotoEntries();

			// Set last update entries
			this.lastUpdate = new Date();

			}

			for(PhotoEntry photo : this.photos){
				if(photo.getSummary().getPlainText().compareTo(imageTitle)==0){
					for(MediaContent mediaContent : photo.getMediaContents()){
						return mediaContent.getUrl();
					}
				}
			}
			return defaultImage;
		}
		catch(Exception e){
			return defaultImage;
		}
	}

}
